package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.Result;
import com.itheima.dto.SetmealDto;
import com.itheima.mapper.SetmealMapper;
import com.itheima.pojo.Setmeal;
import com.itheima.pojo.SetmealDish;
import com.itheima.service.SetmealDishService;
import com.itheima.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {


    @Autowired
    private SetmealDishService setmealDishService;

    @Override
    public void add(SetmealDto setmealDto) {
        save(setmealDto);

        Long id = setmealDto.getId();

        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();

        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(id);
            setmealDishService.save(setmealDish);
        }
    }

    @Override
    public Result deletes(List<Long> ids) {

        for (Long id : ids) {
            Setmeal setmeal = getById(id);
            if(setmeal.getStatus()==1){
                return Result.error("该套餐没有被停售,无法删除");
            }
            LambdaQueryWrapper<SetmealDish> lqw =new LambdaQueryWrapper<>();
            lqw.eq(SetmealDish::getSetmealId,id);
            setmealDishService.remove(lqw);
           removeById(id);
        }
        return Result.success("删除成功");
    }

    @Override
    public void updates(SetmealDto setmealDto) {

        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDto,setmeal);
        updateById(setmeal);

        Long id = setmeal.getId();

        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();

        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(id);
            setmealDishService.save(setmealDish);
        }
    }
}
